import * as api from '../../api/common';
Page({
  data: {
    expand: false,
    ticketId: 0,
    userId: 0, 
    isLike: 0,
    activeTab: 'detail',
    detailContent: '',
    noticeContent: '',
    // recommendations: [{
    //     imageUrl: '../../images/ticket_pic.png',
    //     name: '推荐商品1推荐商品1推荐商品1推荐商品1推荐商品1推荐商品1'
    //   },
    //   {
    //     imageUrl: '../../images/ticket_pic.png',
    //     name: '推荐商品2'
    //   },
    //   {
    //     imageUrl: '../../images/ticket_pic.png',
    //     name: '推荐商品3'
    //   },
    //   {
    //     imageUrl: '../../images/ticket_pic.png',
    //     name: '推荐商品4推荐商品4推荐商品4推荐商品4推荐商品4'
    //   },
    // ],
    fixedLatitude: 39.9042,
    fixedLongitude: 116.4074,
    showPopup: false,
    showService: false,
    dates: [],
    prices: [],
    quantity: 1,
    totalPrice: 0,
    selectedDateIndex: 0,
    selectedPriceIndex: 0,
    ticketDetail: null,
    typeOptions: ['全部票品', '普通票', 'VIP票', 'SVIP票', '优惠/特殊票'], // 票品类型
    recommendList: []
  },
  onExpand() {
    this.setData({
      expand: true
    })
  },
  async isLike() {
    try {
      const {
        data
      } = await api.isLike({
        user_id: this.data.userId,
        ticket_id: this.data.ticketId,
      });
      this.setData({
        isLike: data
      })
    } catch (error) {
      console.error(error);
    }
  },
  async like() {
    try {
      const {
        data
      } = await api.like({
        user_id: this.data.userId,
        ticket_id: this.data.ticketId,
      });
      await this.isLike();
      const info = await api.ticketInfo({
        id: this.data.ticketId
      });
      this.setData({
        [`ticketDetail.click`]: info.data.click ,
      })
      
    } catch (error) {
        console.error(error);
    }
  },
  async getInfo() {
    try {
      const {
        data
      } = await api.ticketInfo({
        id: this.data.ticketId
      });
      const baseUrl = api.baseUrl + '/';

      if (data.img) {
        data.img = baseUrl + data.img;
      }

      if (data.bg_img) {
        data.bg_img = baseUrl + data.bg_img;
      }

      let content =  ''
      let usage =  ''
      if (data.content) {
        content =  data.content.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
      }
      if (data.usage) {
        usage =  data.usage.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
      }

      let guestArray = []
      if (data.guest) {
        guestArray = data.guest
        guestArray.forEach(guest => {
          if (guest.img) {
            guest.img = baseUrl + guest.img;
          }
        });
      }
    
      data.guest = guestArray;

      if (data.start_date) {
        let arr = data.start_date.split('-')
        data.start_date_f = arr[0] + '年' + arr[1] + '月' + arr[2] + '日'
      }
      // 处理并更新数据
      this.setData({
        ticketDetail: data,
        detailContent: content, // 活动介绍
        noticeContent: usage, // 活动须知
      });

      // 在页面加载时计算初始的总价
      this.calculateTotalPrice();
    } catch (error) {
      console.error('获取票据详情失败', error);
    }
  },
  async getRecommend() {
    try {
      const {
        data
      } = await api.recommend({
        id: this.data.ticketId
      });
      const baseUrl = api.baseUrl + '/';
      let arr = data.map(item => ({
        ...item, img: baseUrl + item.img
      }))
      this.setData({
        recommendList: arr
      })
    } catch (error) {
      
    }
  },
  async onLoad(options) {
    const userInfo = tt.getStorageSync('info');
    if (!userInfo || !userInfo.id) {
      tt.redirectTo({
        url: '../loginByAccount/index'
      });
    }
    const id = options.id;
    this.setData({
      ticketId: id,
      userId: userInfo.id
    })
    if (id) {
      await this.isLike();
      await this.getInfo()
      await this.getRecommend()
    }
  },
  calculateTotalPrice() {
    const {
      quantity,
      prices,
      selectedPriceIndex
    } = this.data;
    if (prices.length > 0 && selectedPriceIndex >= 0 && selectedPriceIndex < prices.length) {
      const totalPrice = quantity * prices[selectedPriceIndex].price;
      this.setData({
        totalPrice
      });
    } else {
      // 如果没有选中票价或票价列表为空，默认总价为0
      this.setData({
        totalPrice: 0
      });
    }
  },
  showService() {
    this.setData({
      showService: true
    });
  },
  async showPopup() {
    this.setData({
      showPopup: true
    });
    const {ticketDetail} = this.data;
    try {
      const response = await api.ticketDate({
        id: ticketDetail.id
      });
      const dates = response || [];
      this.setData({
        dates
      });
      this.getPrice()
    } catch (error) {
      console.error('获取场次数据失败:', error);
      tt.showToast({
        title: '获取场次数据失败',
        icon: 'none'
      });
    }
  },
  hidePopup() {
    this.setData({
      showPopup: false,
      showService: false
    });
  },
  async selectDate(event) {
    const index = event.currentTarget.dataset.index;
    this.setData({
      selectedDateIndex: index
    });
    this.getPrice()
  },
  async getPrice(){
    const {dates, selectedDateIndex, ticketDetail} = this.data;
    try {
      const response = await api.ticketPrice({
        id: ticketDetail.id,
        ticketDate: dates[selectedDateIndex].value
      });
      const prices = (response.data || []).map(priceObj => ({
        ...priceObj,
        price: priceObj.price*1 // 确保价格是数字类型
      }));
      this.setData({
        prices
      });
      this.calculateTotalPrice(); // 重新计算总价
    } catch (error) {
      console.error('获取价格数据失败:', error);
      tt.showToast({
        title: '获取价格数据失败',
        icon: 'none'
      });
    }
  },
  selectPrice(event) {
    const index = event.currentTarget.dataset.index;
    this.setData({
      selectedPriceIndex: index
    });
    // 选择票价时重新计算总价
    this.calculateTotalPrice();
  },

  decrease() {
    let {
      quantity
    } = this.data;
    if (quantity > 1) {
      quantity--;
      this.setData({
        quantity
      });
      // 减少数量时重新计算总价
      this.calculateTotalPrice();
    }
  },

  increase() {
    let {
      quantity,
      totalPrice,
      selectedPriceIndex
    } = this.data;
    quantity++;
    totalPrice += this.data.prices[selectedPriceIndex].price; // 增加选中的票价
    this.setData({
      quantity,
      totalPrice
    });
  },
  confirmPurchase() {
    const { quantity, totalPrice, prices, selectedPriceIndex } = this.data;
    const selectedPriceId = prices[selectedPriceIndex]?.id || null;

    tt.navigateTo({
      url: `../placeOrder/index?priceId=${selectedPriceId}&quantity=${quantity}&price=${totalPrice}`,
      success: (res) => {},
      fail: (res) => {},
    });
  },
  switchTab(e) {
    this.setData({
      activeTab: e.currentTarget.dataset.tab
    });
  },
  toMap() {
    const that = this;
    tt.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          // 请求位置权限
          tt.authorize({
            scope: 'scope.userLocation',
            success() {
              that.openLocation();
            },
            fail(e) {
              console.log(e, 666)
              tt.showToast({
                title: '请允许位置权限',
                icon: 'none'
              });
            },
          });
        } else {
          that.openLocation();
        }
      },
      fail() {
        tt.showToast({
          title: '获取设置失败',
          icon: 'none'
        });
      }
    });
  },
  openLocation() {
    let longitude =  Number(this.data.ticketDetail.longitude)
    let latitude = Number(this.data.ticketDetail.latitude)
    tt.getLocation({
      type: 'gcj02',
      success(res) {
        tt.openLocation({
          longitude: Number(longitude),
          latitude: Number(latitude),
          name: '当前位置',
          address: '我的位置',
          scale: 18,
          success() {
            tt.showToast({
              title: 'success',
              icon: 'success'
            });
          },
          fail(res) {
            tt.showToast({
              title: res.errMsg,
              icon: 'none'
            });
          }
        });
      },
      fail(res) {
        tt.showToast({
          title: res.errMsg,
          icon: 'none'
        });
      }
    });
  },
  onShareAppMessage(ShareOption) {
    const baseUrl = api.baseUrl + '/';
    const name = this.data.ticketDetail.name;
    const imageUrl = baseUrl + this.data.ticketDetail.img;
    const query = "id=" +  this.data.ticketDetail.id;
    return {
      title: name, 
      desc: "",
      query: query,
      imageUrl: imageUrl, 
      success() {
        console.log("分享成功");
      },
      fail() {
        console.log("分享失败");
      },
    }
  }
})